#include "cfgcom.h"
#include "ui_cfgcom.h"

#include "iconfont.h"
#include <QMessageBox>
#include <qdatetime.h>

CfgCom::CfgCom(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CfgCom),
    enableCache(false)
{
    ui->setupUi(this);
    uiInit();
    searchPort();
    serialPortInit();
}

CfgCom::~CfgCom()
{
    delete ui;
}

void CfgCom::uiInit()
{
    ui->btn_refresh->setFont(IconFont::IconFontInstance()->iconFont);
    ui->btn_refresh->setText(QChar(0xe610));
    ui->btn_refresh->setStyleSheet("color:black;font-size:26px;");
    ui->cb_baud->setCurrentIndex(3);
    setState("无操作","#909399");
}

void CfgCom::searchPort()
{
    // 查找可用的串口设备
    QList<QSerialPortInfo> serialPortInfos = QSerialPortInfo::availablePorts();
    ui->cb_com->clear();
    // 将可用串口设备添加到 QComboBox 中
    foreach (const QSerialPortInfo &serialPortInfo, serialPortInfos) {
        ui->cb_com->addItem(serialPortInfo.portName());
    }
}

void CfgCom::serialPortInit()
{
    serialPort = new QSerialPort(this);
    tempTimer = new QTimer();

    connect(serialPort,&QSerialPort::readyRead,[&](){
        tempArrayData.append(serialPort->readAll());
        tempTimer->start(ui->lineEdit_cache_time->text().toInt());
    });
    // 缓存完整数据
    connect(tempTimer,&QTimer::timeout,this,&CfgCom::cacheDate);

}

void CfgCom::setState(QString state,QString color)
{
    QString text = "<span style='color: #4b5450;'>采集状态：</span>"
                   "<span style='color:%1;font-weight:600;white-space: pre;'>%2</span>";
    ui->lbl_msg->setText(text.arg(color).arg(state));
}

void CfgCom::writeData(QString data)
{
    serialPort->write(data.toUtf8());
}

void CfgCom::cacheDate()
{
    enableCache = true;
    tempTimer->stop();//关闭定时器
    emit sendData(tempArrayData);
    ui->plainTextEdit->appendPlainText(timeStamp() + " -> " + tempArrayData);
    tempArrayData.clear();//清除缓冲区
}

void CfgCom::on_btn_refresh_clicked()
{
    searchPort();
}


void CfgCom::on_cb_com_currentTextChanged(const QString &arg1)
{
    portName = arg1;
}


void CfgCom::on_btn_start_clicked()
{
    serialPort->setPortName(portName);
    serialPort->setBaudRate(baud);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (!serialPort->open(QIODevice::ReadWrite)) {
        QMessageBox::warning(this,QString("提示"),QString("串口%1，%2").arg(portName).arg(serialPort->errorString()));
        return;
    }
    setState("数据采集中...","#67c23a");
}


void CfgCom::on_cb_baud_currentTextChanged(const QString &arg1)
{
    baud = arg1.toInt();
}


void CfgCom::on_btn_stop_clicked()
{
    serialPort->close();
    setState("停止采集","#f56c6c");
}

//时间戳
QString CfgCom::timeStamp()
{
    //将时间对面按照一定的格式转换为字符串对象
    QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间

    QString time_stamp = dateTime .toString("hh:mm:ss");//格式化时间

    return  "[" + time_stamp + "] : ";

}
